<template>
  <van-icon
    @click="onCollect"
    :color="value ? '#ffa500' : ''"
    :name="value ? 'star' : 'star-o'"
    :loading="loading"
  />
</template>

<script>
import { addCollect, deleteCollect } from '@/api/article'
export default {
  name: 'CollectArticle',
  props: {
    value: {
      type: Boolean,
      required: true
    },
    articleId: {
      type: [Number, String, Object],
      required: true
    }
  },
  data () {
    return {
      loading: false
    }
  },
  methods: {
    async onCollect () {
      this.loading = true
      try {
        if (this.value) {
          // 收藏，点击取消
          await deleteCollect(this.articleId)
        } else {
          // 未收藏，收藏
          await addCollect(this.articleId)
        }
        this.$emit('input', !this.value)
        // 两种方法 宏任务和微任务
        setTimeout(() => {
          this.$toast.success(this.value ? '收藏成功' : '取消收藏')
        }, 0)
        // this.$toast.success(!this.value ? '收藏成功' : '取消收藏')
      } catch (error) {
        this.$toast.fail('操作失败，请重试！')
      }
      this.loading = false
    }
  }
}
</script>

<style lang="less" scoped></style>
